class Solution {
    int n;
    int m;
    public int minFlips(int[][] grid) {
        n= grid.length;
        m=grid[0].length;
        int sum1=0;
        int sum2=0;
        if(n%2==0){
            sum1=findEven(grid,1);
        }else{
            sum1=findOdd(grid,1);
        }
        if(m%2==0){
            sum2=findEven(grid,0);
        }else{
            sum2=findOdd(grid,0);
        }
        return Math.max(sum1,sum2);
    }
    public int findOdd(int[][] grid,int fg){
        //奇数
        int sum=0;
        if(fg==1){
            //列是回文
            int t=n/2;

            for (int i = 0; i < m; i++) {
                int r=t+1;
                while(r<n){
                    if(grid[r][i]!=grid[2*t-r][i]){
                        sum++;
                    }
                    r++;
                }
            }
        }else{
            //行是回文
            int t=m/2;

            for (int i = 0; i < n; i++) {
                int r=t+1;
                while(r<m){
                    if(grid[i][r]!=grid[i][2*t-r]){
                        sum++;
                    }
                    r++;
                }
            }
        }
        return sum;
    }
    public int findEven(int[][] grid,int fg){
        //偶数
        int sum=0;
        if(fg==1){
            //列是回文

            for (int i = 0; i < m; i++) {
                int r=n/2;
                if(r==0){
                    break;
                }
                int l=r-1;
                while(r<n){
                    if(grid[i][l]!=grid[i][r]){
                        sum++;
                    }
                    r++;
                    l--;
                }
            }
        }else{
            //行是回文

            for (int i = 0; i < n; i++) {
                int r=m/2;
                if(r==0){
                    break;
                }
                int l=r-1;
                while(r<m){
                    if(grid[i][l]!=grid[i][r]){
                        sum++;
                    }
                    r++;
                    l--;
                }
            }
        }
        return sum;
    }
}